import { useEffect, useMemo, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import classnames from 'classnames'
import { Button, Card, Popover, Timeline } from 'antd'

import { VCenterEmpty } from '@/components/VCenterEmpty'
import { apiGetOriginalRouteInfo, apiUpdateStatus } from './apis'
import { IOriginalRouteInfo } from './interface'
import styles from './styles.module.less'

interface IProps {
  waybillNo: string
}

export const OriginalRoute = (props: IProps) => {
  const { waybillNo } = props
  const [originalRouteInfo, setOriginalRouteInfo] = useState<IOriginalRouteInfo>({} as IOriginalRouteInfo)
  const [loading, setLoading] = useState<boolean>(false)

  // 请求接口
  const initData = useMemoizedFn(async (isinit?: boolean) => {
    try {
      if (isinit) setLoading(true)
      const data = await apiGetOriginalRouteInfo(waybillNo)
      setOriginalRouteInfo(data)
    } finally {
      if (isinit) setLoading(false)
    }
  })

  const items = useMemo(() => {
    const currentItems = (originalRouteInfo?.originalRouteList || []).map((item, index) => {
      return {
        children: (
          <div className={styles.routeContain}>
            <div className={classnames(styles.textNew, index > 0 ? styles.textFilter : '')}>{item.originalRoute}</div>
            <div className={styles.textTime}>{item.occurDate}</div>
          </div>
        ),
        color: index === 0 ? 'blue' : 'gray',
      }
    })
    return currentItems
  }, [originalRouteInfo?.originalRouteList])

  useEffect(() => {
    initData(true)
  }, [initData, waybillNo])

  return (
    <Card
      className={styles.card}
      title="原始路由"
      loading={loading}
      extra={
        originalRouteInfo?.markStatus ? null : (
          <Popover
            overlayInnerStyle={{ width: '110px' }}
            content={
              <Button
                type="link"
                onClick={async () => {
                  await apiUpdateStatus({ status: 1, waybillNo })
                  setOriginalRouteInfo(pre => {
                    const newValue = { ...pre }
                    return { ...newValue, markStatus: 1 }
                  })
                }}
              >
                标记为已读
              </Button>
            }
          >
            <div className={styles.extra}>未读</div>
          </Popover>
        )
      }
    >
      {!originalRouteInfo ? (
        VCenterEmpty.render()
      ) : (
        <div className={styles.box}>
          <Timeline items={items} />
        </div>
      )}
    </Card>
  )
}
